package com.example.demo.service;

import com.example.demo.dao.UserDao;
import com.example.demo.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author chenzhihua@skyworth.com
 * @version 1.0
 * @since 2021/11/9 13:48
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        //查询用户
        //UserDetails user = User.withUsername("zhangsan").password("$2a$10$WdmJiAyEp3IKHeczycQWWOn/NgU1CGG/FufZ/KhgKc0HjIFps99xK").authorities("p1").build();

        //将来连接数据库根据账号查询用户信息
        UserDto userDto = userDao.getUserByUsername(name);

        if(userDto == null){
            //如果用户查不到，返回null，由provider来抛出异常
            return null;
        }

        //根据用户的id查询用户的权限
        List<String> permissions = userDao.findPermissionsByUserId(userDto.getId());
        //将permissions转成数组
        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);
        UserDetails userDetails = User
                .withUsername(userDto.getUsername())
                .password(userDto.getPassword())
                .authorities(permissionArray)
                .build();
        return userDetails;

    }
}
